package com.wmm.servlet.classes;

import com.wmm.bean.Classes;
import com.wmm.bean.PageBean;
import com.wmm.service.ClassesService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "UpdateClassInfoServlet", urlPatterns = "/updateClassInfo")
public class UpdateClassInfoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //1.  接收前端传来的班级信息参数
        String classNo = request.getParameter("classNo");
        String className = request.getParameter("className");
        String grade = request.getParameter("grade");
        String teacher = request.getParameter("teacher");
        String position = request.getParameter("position");
        String slogan = request.getParameter("slogan");

        Classes myclass = new Classes();
        myclass.setClassNo(classNo);
        myclass.setClassName(className);
        myclass.setClassNumber(Integer.parseInt(position));
        myclass.setClassSlogan(slogan);
        myclass.setClassTeacher(teacher);
        myclass.setGrade(grade);
        ClassesService classService = new ClassesService();
        HttpSession session = request.getSession();
        String classname = (String) session.getAttribute("classname");
        String grade1 = (String) session.getAttribute("grade");
        boolean update = classService.updateClassesServer(myclass);
        if(update) {
            System.out.println("修改班级成功");
            //2. 调用service查询
            PageBean<Classes> queryList = classService.findClassesByPage("1","5");
            //3. 将PageBean存入session
            session.setAttribute("queryClassList",queryList);
            System.out.println(queryList.toString());
            //4. 转发到show.jsp
            request.getRequestDispatcher("showClass.jsp").forward(request,response);



        } else {
            PrintWriter writer = response.getWriter();
            writer.println("<script>");
            writer.println("alert('该记录的班级名与年级有问题，请重新输入')");
            writer.println("window.location.href = 'updateClass.jsp' ");
            writer.println("</script>");
            writer.close();

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
